﻿using System.Diagnostics;
using System.ServiceProcess;
using System.Timers;
using System;
using System.Linq;
using Citi.Scheduler.Domain;
using Citi.Helpers;
using System.Configuration;
using System.Threading;

namespace Citi.Scheduler.WindowsServices
{
    partial class Monitor : ServiceBase
    {
        private const string EventSource = "Citi Monitor Service";
        private const string EventLogName = "Citi Monitor Service Log";
        private System.Timers.Timer timer = new System.Timers.Timer();
        private static Machine Machine { get; set; }
        private static string NetworkUser { get { return ConfigurationManager.AppSettings["NetworkUser"]; } }
        private static string NetWorkPassword { get { return ConfigurationManager.AppSettings["NetWorkPassword"]; } }
        private static string Domain { get { return NetworkUser.Split('\\')[0]; } }
        private static string UserWithoutDomain { get { return NetworkUser.Split('\\')[1]; } }

        public Monitor()
        {
            InitializeComponent();

            try
            {
                if (!EventLog.SourceExists(EventSource)) EventLog.CreateEventSource(EventSource, EventLogName);
            }
            catch { }
        }

        private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            if (Machine.BackupPosition.HasValue && Machine.BackupPosition > 0)
            {
                var machinesBackup = Machine.SelectByCenterBackupOrder(MachineCenter.Monitor).Where(x => x.BackupPosition < Machine.BackupPosition);

                foreach (var machine in machinesBackup)
                {
                    var service = new MachineService(machine, ServiceName, Domain, NetworkUser, NetWorkPassword);

                    if (service.GetServiceStatus() == ServiceControllerStatus.Running)
                    {
                        //Console.WriteLine("Backup is not needed at this time");
                        return;
                    }

                    Thread.Sleep(8000);

                    service = new MachineService(machine, ServiceName, Domain, NetworkUser, NetWorkPassword);

                    if (service.GetServiceStatus() == ServiceControllerStatus.Running)
                    {
                        //Console.WriteLine("Backup is not needed at this time");
                        return;
                    }
                }
            }

            EventLog.Log = EventLogName;
            EventLog.Source = EventSource;
            MonitorAction.ProcessRunning = false;
            MonitorAction.EventLog = EventLog;
            MonitorAction.StartEngine();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                Console.OpenStandardOutput();

                Machine = new Machine().GetByHostName(Environment.MachineName, MachineCenter.Monitor);

                if (Machine == null)
                {
                    EventLog.WriteEntry("Machine isn't a Monitor Center Machine", EventLogEntryType.Information);
                    throw new Exception("Machine does not exist in the database");
                    //return;
                }

                timer.Elapsed += TimerOnElapsed;
                timer.Interval = 180000;
                timer.Start();
            }
            catch (Exception e)
            {
                LogUtil.PathLogErro = MonitorAction.ErrorLog;
                LogUtil.LogError(MonitorAction.EventLog, e);
            }
        }

        protected override void OnStop()
        {
            timer.Stop();
        }
    }
}
